package com.netty.chatRoom;

import com.netty.chatRoom.message.LoginRequestMessage;
import com.netty.chatRoom.message.Message;
import com.netty.chatRoom.protocol.MessageCodecSharable;
import com.netty.chatRoom.server.config.Config;
import com.netty.chatRoom.server.serializer.Serializer;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.logging.LoggingHandler;

import java.util.List;

public class TestSerializeAlogrithm {
    public static void main(String[] args) throws Exception {
        LoggingHandler LOGIN_HANDLER = new LoggingHandler();
        EmbeddedChannel channel = new EmbeddedChannel(
                LOGIN_HANDLER,
                new MessageCodecSharable(),
                LOGIN_HANDLER
        );
        LoginRequestMessage message = new LoginRequestMessage("xunmeng", "123");
//        channel.writeOutbound(message);
        channel.writeInbound(encode(message));
    }

    protected static ByteBuf encode(Message message) throws Exception {
        // 将消息传递给外界，需要将内部消息编码
        // 将消息传递给外界，需要将内部消息编码
        ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer();
        // 1. 4字节魔数
        byteBuf.writeBytes(new byte[]{'X','U','N','M'});
        // 2. 协议版本号，1字节
        byteBuf.writeByte(1);
        // 3. 序列化算法 ，1字节
        byteBuf.writeByte(Config.getSerializerAlgorithm().ordinal());// 0代表用jdk进行序列化 1代表用JSON序列化
        // 4. 指令类型，1字节
        byteBuf.writeByte(message.getMessageType());
        // 5. 请求序号，4字节
        byteBuf.writeInt(message.getSequenceId());
        // 6. 无意义,对齐填充,1字节
        byteBuf.writeByte(0xff);
        // 7. 获取内容的字节数
        Serializer.Algorithm algorithm = Serializer.Algorithm.values()[Config.getSerializerAlgorithm().ordinal()];
        byte[] content = algorithm.enserialize(message);
        // 8. 数据长度，4字节
        byteBuf.writeInt(content.length);
        // 9. 数据内容
        byteBuf.writeBytes(content);
        return byteBuf;
    }
}
